// const useragent = require('useragent');
// const DeviceDetector = require('device-detector-js');
const tools = require('./tools')
const uaParse = require('ua-parser-js')
/**
 * ua
 * @param uaStr
 * @return {{osVersion: *, model: *, osName: *, manufacturer: (*|string)}}
 */
const buildUA = (uaStr)=>{
    const ua = new uaParse(uaStr).getResult();
    // const deviceDetector = new DeviceDetector();
    // const result = deviceDetector.parse(uaStr);
    return {
        userAgent: {
            // manufacturer:result.device && result.device.brand,//设备制造商，例如Apple
            // model: result.device && result.device.type,
            // osName: result.os && result.os.name,
            // osVersion: result.os && result.os.version,
            // platform:result.client && result.client.type,
            // userAgent:ua
            borderGroup: ua.engine.name,
            borderName: ua.engine.name,//浏览器名称
            borderType: ua.browser.name,//浏览器类型
            browserManufacturer: ua.device.vendor,//浏览器厂商
            browserVersion: ua.browser.version,//浏览器版本
            deviceManufacturer: ua.device.vendor,//设备厂商
            devicetype: ua.device.type,//设备类型
            os: ua.os.name,//设备系统
            osName: ua.os.versionName,//设备系统名称
            osVersion: ua.os.version,//设备系统版本
            borderRenderingEngine: ua.engine.name
        }
    }
}


/**
 * ip
 * @param ip
 * @return {{country: *, province: *, city: *, isp: *, district, location: string}}
 */
const buildIP = async (ip)=>{
    const info = await tools.getGeoInfo(ip).catch(e=>{
        console.log(e,'getGeoInfo')
        return Promise.reject('getGeoInfo_error')
    })
    return new Promise(async (resolve,reject)=>{
        if(info){
            resolve({
                IPAddress:{
                    isp:info.isp,//网络运营商
                    country:info.country,
                    province:info.province,
                    city:info.city,
                    district:info.district,
                    location:info.rectangle,
                    ip:ip,
                    ipAddress:ip,
                },
                country:info.country,
                province:info.province,
                city:info.city,
                district:info.district,
                ip:ip,
                location:info.rectangle
            })
        }else{
            reject('getGeoInfo_error1')
        }
    })
}


const buildOther = (obj, pathList) =>{
    const properties = obj.properties || obj
    const nowDate = new Date()
    return{
        logId:obj.logId,
        clientId:obj.clientId,
        pageName:properties.pageName||'',//页面名称
        fromPage:properties.fromPage||'',//来源页面名称
        shopId:properties.shopId||'',//店铺ID
        resourceId:properties.resourceId||'',//资源ID
        activityId:properties.activityId||'',//活动ID
        moduleName:properties.moduleName||'',//模块名称
        date:tools.dateFormat(nowDate,'YYYY-MM-DD'),//日期
        hour:tools.dateFormat(nowDate,'hh'),
        minute:tools.dateFormat(nowDate,'mm'),
        visitFromChannel:properties.visitFromChannel||'',//访问来源渠道
        type:properties.type,//埋点类型：page,event
        eventName:properties.eventName,//事件名称
        stayTime:properties.event_duration*1000,//停留时间
        screenWidth:properties['$screen_width'],//屏幕宽度
        screenHeight:properties['$screen_height'],
        networkType:properties['$network_type'],//网络类型
        wxAppCityName: properties.cityName || '',//用户切换城市
        businessGroupId:properties.businessGroupId,//企业微信群id
        staffId:properties.staffId,//员工id
        corpId:properties.corpId,//微信企业id
        shareUserId:properties.shareUserId,//分享人id
        couponId:properties.couponId,//优惠券ID
        lineType:properties['$network_type'],//网络类型
        shopType:properties.shopType,
        spName:properties.spName,
        others:{},
        enterpriseNumber:(properties && properties.enterpriseNumber)||'',//企业编号
        enterpriseGrade: (properties && properties.enterpriseGrade) || '',//企业等级
        wxOpenId: properties.wxOpenId,//微信用户id
        latestScene: properties['$latest_scene'] || '', //最新场景
        referrer: pathList.find(item => item.path === properties['$referrer'])?.name || properties['$referrer'] || '', // 页面跳转来源
        referrerTitle: pathList.find(item => item.path === properties['$referrer'])?.page || properties['$referrer_title'] || '', // 页面跳转来源信息
        url: properties['$url'] || '', // 页面跳转来源全路径
        urlPath: pathList.find(item => item.path === properties['$url_path'])?.name || properties['$url_path'] || '', // 页面跳转来源
        urlPathTitle: pathList.find(item => item.path === properties['$url_path'])?.page || '', // 页面跳转来源
        isFirstDay: properties['$is_first_day'] || '', // 是否是用户首次访问
        mpClientAppVersion: properties['$mp_client_app_version'] || '', // 微信版本号
        mpClientBasicLibraryVersion: properties['$mp_client_basic_library_version'] || '', // 微信基础库版本号
        terminal: 'WX_APP'
    }
}
/**
 * 构建用户信息
 * @param obj
 * @param {string} obj.registerChannel 注册渠道
 * @param  {string} obj.enterpriseId 用户当前所在企业
 * @param {string} obj.isAdmin  是否是所在企业管理员
 * @param {string} obj.identity  用户身份
 * @param {string} obj.enterpriseNumber 企业编号
 * @param {string} obj.enterpriseGrade 企业等级
 *@param {string} lenovoId lenovoId
 * @return {{uid: (*|string), enterpriseGrade: (*|string), enterpriseNumber: (*|String|StringConstructor|string), registerChannel: (*|string), admin: ({user}|*|boolean), enterpriseId: (*|String|StringConstructor|string), userIdentity: (string)}}
 */
 const buildUser = (obj,lenovoId) =>{
    return {
        uid: lenovoId || '',//用户id
        registerChannel: obj?.registerChannel || '',//用户注册渠道
        enterpriseId: obj?.enterpriseId || '',//用户当前所在企业
        admin: obj?.isAdmin || false,//是否是所在企业管理员
        userIdentity: obj?.identity,//访问用户身份
        enterpriseNumber: obj?.enterpriseNumber||'',//企业编号---优先取传递的，没传递取登录用户的
        enterpriseGrade: obj?.enterpriseGrade || ''//企业等级---优先取传递的，没传递取登录用户的
    }
}
// /**
//  * 获取路径与埋点名称去陪关系
//  * @param obj
//  * @return {{uid: (*|string), enterpriseGrade: (*|string), enterpriseNumber: (*|String|StringConstructor|string), registerChannel: (*|string), admin: ({user}|*|boolean), enterpriseId: (*|String|StringConstructor|string), userIdentity: (string)}}
//  */
//  const buildPath = (obj,lenovoId) =>{
//     return {
//         uid: lenovoId || '',//用户id
//         registerChannel: obj?.registerChannel || '',//用户注册渠道
//         enterpriseId: obj?.enterpriseId || '',//用户当前所在企业
//         admin: obj?.isAdmin || false,//是否是所在企业管理员
//         userIdentity: obj?.identity,//访问用户身份
//         enterpriseNumber: obj?.enterpriseNumber||'',//企业编号---优先取传递的，没传递取登录用户的
//         enterpriseGrade: obj?.enterpriseGrade || ''//企业等级---优先取传递的，没传递取登录用户的
//     }
// }

module.exports = {
    buildUA,
    buildIP,
    buildOther,
    buildUser
};
